package com.my.content.ui_homework.fragment.HomePage;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.my.content.ui_homework.Constant;
import com.my.content.ui_homework.R;
import com.my.content.ui_homework.helper.OkHttpClientHelper;

import java.io.IOException;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomePageItemFragment extends Fragment {


    private ListView mLv;
    private HomePageAdapter mAdapter;
    private List<Stars.RowsBean> mList;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 1){
                mList = (List<Stars.RowsBean>) msg.obj;
                mAdapter.setData(mList);
            }
        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home_page_item, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mLv = (ListView) view.findViewById(R.id.home_page_item_lv);
        mAdapter = new HomePageAdapter(getActivity());
        mLv.setAdapter(mAdapter);
        initData();
    }
    private void initData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String beanJson = OkHttpClientHelper.getStringFromURL(getActivity(), Constant.STAR_ONE_URL, null);
                    Stars bean = mAdapter.parseJsontoBean(beanJson);
                    final List<Stars.RowsBean> mList = bean.getRows();

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Message message = Message.obtain();
                            message.what = 1;
                            message.obj = mList;
                            mHandler.sendMessage(message);
                        }
                    });
                } catch (IOException e) {
                }
            }
        }).start();
    }
}
